﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows;
using System.Windows.Media;

namespace WpfLibrary;

public class DragUtility
{
    public static Window? GetParentWindow(TabItem? tabItem)
    {
        if (tabItem == null)
        {
            return null;
        }
        var tabControl = tabItem.Parent as TabControl;
        if (tabControl == null)
        {
            return null;
        }
        return GetParentWindow(tabControl);
    }
    public static Window? GetParentWindow(TabControl? tabControl)
    {
        if (tabControl == null)
        {
            return null;
        }
        var frameworkElement = tabControl.Parent as FrameworkElement;
        while (frameworkElement != null)
        {
            if (frameworkElement is Window)
            {
                return frameworkElement as Window;
            }
            else
            {
                frameworkElement = frameworkElement.Parent as FrameworkElement;
            }
        }
        return null;
    }

    public static object? GetDataObjectFromItemsControl(ItemsControl itemsControl, Point p)
    {
        UIElement? element = itemsControl.InputHitTest(p) as UIElement;
        while (element != null)
        {
            if (element == itemsControl)
                return null;

            object data = itemsControl.ItemContainerGenerator.ItemFromContainer(element);
            if (data != DependencyProperty.UnsetValue)
            {
                return data;
            }
            element = VisualTreeHelper.GetParent(element) as UIElement;
        }
        return null;
    }
}
